package com.zjw.socket.demo.starter.messageService.service.impl;


import com.zjw.socket.demo.starter.annotation.core.Bean;
import com.zjw.socket.demo.starter.messageService.service.IConnectSession;
import com.zjw.socket.demo.starter.messageService.service.IUserPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Bean(name = "SimpleUserPool")
public class SimpleUserPool implements IUserPool {

  /**
   * 在线连接池，只有在线用户存在此中。
   */
  private final Map<Long, IConnectSession> pool = new ConcurrentHashMap<>();

  @Override
  public void connect(long uid, IConnectSession session) {
    IConnectSession old = pool.put(uid, session);
    if (old != null && old != session) {
      old.disconnect();
    }
  }

  @Override
  public void disconnect(long uid) {
    IConnectSession remove = pool.remove(uid);
    if (remove != null) {
      remove.disconnect();
    }
  }

  @Override
  public IConnectSession getConnectSession(long uid) {
    return pool.get(uid);
  }

  @Override
  public int size() {
    return pool.size();
  }
}
